package com.unicampmaps;	

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.preference.PreferenceManager;

public class VenueProvider extends ContentProvider {
	private static final String TAG = VenueProvider.class.getSimpleName();
	
	public static final Uri CONTENT_URI = Uri.parse("content://com.unicampmaps.venueprovider");
	public static final String SINGLE_RECORD_MIME_TYPE = "vnd.android.cursor.item/vnd.unicampmaps.venue";
	public static final String MULTIPLE_RECORDS_MIME_TYPE = "vnd.android.cursor.dir/vnd.unicampmaps.mvenues";
	
	protected DbHelper dbHelper; //
	
	// system calls onCreate() when it starts up the provider.
	@Override
	public boolean onCreate() {
		System.out.println("ONCREATE Provider");
		// get access to the 1database helper
		dbHelper = new DbHelper(getContext());
		// open to read only
		dbHelper.getReadableDatabase();
		
		//Chama o update via internet
		DatabaseUpdater dbUpdater = new DatabaseUpdater(this.getContext(), dbHelper.getWritableDatabase());
		dbUpdater.execute(DatabaseUpdater.URI);
		
		return true;
	}

	@Override
	public String getType(Uri uri) {
		return this.getArgsValue(uri) < 0 ? MULTIPLE_RECORDS_MIME_TYPE
				: SINGLE_RECORD_MIME_TYPE;
	}

	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			long id = db.insertOrThrow(VenueData.TABLE, null, values);
			if (id == -1) {
				throw new RuntimeException(
						String.format(
								"%s: Failed to insert [%s] to [%s] for unknown reasons.",
								TAG, values, uri)); //
			} else {
				return ContentUris.withAppendedId(uri, id); //
			}
		} finally {
			db.close();
		}
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		String argName = this.getArgsName(uri);
		long argValue = this.getArgsValue(uri);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		
		System.out.println("argName: " + argName);
		System.out.println("argValue: " + argValue);
		if(argName!=null){
			if (argName.equals(VenueData.C_TYPE)) {
				return db.query(VenueData.TABLE, projection, VenueData.C_TYPE+ "=" + argValue, null, null, null, null);
			} 
			else if (argName.equals(VenueData.C_ID)) {
				return db.query(VenueData.TABLE, projection, VenueData.C_ID+ "=" + argValue, null, null, null, null, "1");
			} else {
				return db.query(VenueData.TABLE, projection, selection, selectionArgs, null, null, sortOrder);
			}
		}else{
			return db.query(VenueData.TABLE, projection,selection,selectionArgs,null,null,sortOrder);
		}
	}

	public Cursor queryByID(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		String argName = this.getArgsName(uri);
		long argValue = this.getArgsValue(uri);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		
		System.out.println("argName: " + argName);
		System.out.println("argValue: " + argValue);
		
		if (argName.equals(VenueData.C_TYPE)) {
			return db.query(VenueData.TABLE, projection, VenueData.C_TYPE+ "=" + argValue, null, null, null, null);
		} 
		else if (argName.equals(VenueData.C_ID)) {
			System.out.println("QUERY BY ID");
			return db.query(VenueData.TABLE, projection, VenueData.C_ID+ "=" + argValue, null, null, null, null, "1");
		} else {
			return db.query(VenueData.TABLE, projection, selection, selectionArgs, null, null, sortOrder);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		long id = this.getArgsValue(uri);
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			if (id < 0) {
				return db.update(VenueData.TABLE, values, selection, selectionArgs);
			} else {
				return db.update(VenueData.TABLE, values, VenueData.C_ID + "=" + id, null);
			}
		} finally {
			db.close();
		}
	}

	private String getArgsName(Uri uri) {
		String[] segments = uri.getPath().split("/");
		String argName=null;
		if(segments.length==3)
			argName=segments[segments.length-2];
		return argName;
	}

	private long getArgsValue(Uri uri) {
		String argValue = uri.getLastPathSegment();
		
		if (argValue != null) {
			try {
				return Long.parseLong(argValue); //
			} catch (NumberFormatException e) { //
				// at least we tried
			}
		}
		return -1;
	}
	
	//DbHelper implementations
	class DbHelper extends SQLiteOpenHelper {
		static final String DATABASE = "venues.db";
		static final int VERSION = 2;
		
		public DbHelper(Context context) {
			super(context, DATABASE, null, VERSION);
	        
			System.out.println("construct DBHelper");
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			System.out.println("ONCREATE DBHelper");
			VenueData.onCreate(db);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			VenueData.onUpgrade(db, oldVersion, newVersion);
			System.out.println("ONUPDRADE DBHelper");
		}
	}

}
